package com.loongxun.playwithyou.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.App;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.bean.Member;
import com.loongxun.playwithyou.bean.MemberGame;
import com.loongxun.playwithyou.bean.Merchant;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.ui.PickerDialog;
import com.loongxun.playwithyou.util.ReflectionUtils;
import com.loongxun.playwithyou.util.ToastView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cz.msebera.android.httpclient.util.TextUtils;

/**
 * 去下单
 * Created by Administrator on 2017/7/31.
 */
public class ToOrderActivity extends Activity implements View.OnClickListener{

    private Context context;
    private SendRequest send;
    private Member member = new Member();
    private List<Merchant> merchants = new ArrayList<>();

    private ImageLoader imageLoader = ImageLoader.getInstance();
    //用户编辑器
    private SharedPreferences share;
    private SharedPreferences.Editor editor;

    private ImageView iv_play_user_img;
    //陪练名、游戏种类
    private TextView tv_play_user_name,
            tv_play_game,tv_play_date,tv_play_date_num,tv_play_address;
    private EditText tv_play_phone;
    private LinearLayout ll_play_user;

    //游戏id,陪玩时长,手机号,地址id,预约时间
    private String memberGameId = "", hoursNum = "", userPhone = "",
            merchantId = "", playStartTime = "",userId;

    //订单号，描述，价格
    private String orderNo,subject,price;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
    private SimpleDateFormat sdfDD = new SimpleDateFormat("yyyy-MM-dd ");
    private SimpleDateFormat sdfHH = new SimpleDateFormat("HH:00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_to_order);
        context = ToOrderActivity.this;
        member.setMember_id(getIntent().getIntExtra("member_id", 0));

        share = context.getSharedPreferences("userInfo", 0);
        editor = share.edit();
        userId = share.getString("user_id", "");
        userPhone = share.getString("user_phone","");

        try {
            send = new SendRequest();
            send.memberId = member.getMember_id()+"";
            //陪玩人员详情
            nHttpClient.getAll(ApiInterface.INDEX_TO_ORDER, send.toMemberInfoJson().toString(), indexHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
        initView();
    }

    private void initView() {
        iv_play_user_img = (ImageView) findViewById(R.id.iv_play_user_img);
        tv_play_user_name = (TextView) findViewById(R.id.tv_play_user_name);
        ll_play_user = (LinearLayout) findViewById(R.id.ll_play_user);

        tv_play_game = (TextView) findViewById(R.id.tv_play_game);
        tv_play_date = (TextView) findViewById(R.id.tv_play_date);
        tv_play_date_num = (TextView) findViewById(R.id.tv_play_date_num);
        tv_play_address = (TextView) findViewById(R.id.tv_play_address);
        tv_play_phone = (EditText) findViewById(R.id.tv_play_phone);
        tv_play_game.setOnClickListener(this);
        tv_play_date.setOnClickListener(this);
        tv_play_date_num.setOnClickListener(this);
        tv_play_address.setOnClickListener(this);

        findViewById(R.id.tv_go_to_order).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        ToastView toast;
        switch (view.getId()){
            //游戏种类
            case R.id.tv_play_game:
                intent = new Intent(context, PickerDialog.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("member", member);
                bundle.putInt("type", 1);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
                break;
            //预约时间
            case R.id.tv_play_date:
                intent = new Intent(context, PickerDialog.class);
                intent.putExtra("type",2);
                startActivityForResult(intent, 2);
                break;
            //陪玩时长
            case R.id.tv_play_date_num:
                intent = new Intent(context, PickerDialog.class);
                intent.putExtra("type",3);
                startActivityForResult(intent, 3);
                break;
            //预约地址
            case R.id.tv_play_address:
                intent = new Intent(context, PickerDialog.class);
                intent.putExtra("member", member);
                intent.putExtra("type",4);
                startActivityForResult(intent, 4);
                break;
            //确认下单
            case R.id.tv_go_to_order:
                userPhone = tv_play_phone.getText().toString().trim();
                if ("".equals(userId)){
                    toast = new ToastView(context, "请登录");
                    toast.show();
                }else if ("".equals(memberGameId)){
                    toast = new ToastView(context, "请选择游戏种类");
                    toast.show();
                }else if ("".equals(playStartTime)){
                    toast = new ToastView(context, "请选择预约时间");
                    toast.show();
                }else if ("".equals(hoursNum)){
                    toast = new ToastView(context, "请选择陪玩时长");
                    toast.show();
                }else if ("".equals(merchantId)) {
                    toast = new ToastView(context, "请选择预约地址");
                    toast.show();
                }else if(TextUtils.isEmpty(userPhone)){
                    toast = new ToastView(context, "请输入手机号");
                    toast.show();
                }else if (!ReflectionUtils.isPhone(userPhone)) {
                    toast = new ToastView(context, "请填写您的联系方式");
                    toast.show();
                }else {
                    try {
                        send = new SendRequest();
                        send.memberGameId = memberGameId;
                        send.userId = userId;
                        send.hoursNum = hoursNum;
                        send.userPhone = userPhone;
                        send.merchantId = merchantId;
                        send.playStartTime = playStartTime;
                        //保存订单
                        //{"memberGameId":"38","userId":"39","hoursNum":"1","userPhone":"15092710472","merchantId":"1","playStartTime":"2017-07-09 08:00"}
                        nHttpClient.getAll(ApiInterface.INDEX_SAVE_ORDER, send.toSaveOrderJson().toString(), orderHandler);
                    }catch (Exception e){
                        toast = new ToastView(context, "参数错误");
                        toast.show();
                    }
                }
                break;
            default:
                break;
        }
    }

    private void toPlayActivity(){
        Intent intent = new Intent(context, ToPlayAcitvity.class);
        intent.putExtra("orderNo",orderNo);
        intent.putExtra("subject",subject);
        intent.putExtra("price",price);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            String num = data.getStringExtra("picker_left");
            if (requestCode == 1) {
                if ("".equals(num)) {
                    memberGameId = member.getMemberGames().get(0).getMember_game_id()+"";
                    tv_play_game.setText(member.getMemberGames().get(0).getGame_name());
                }else {
                    for (int i = 0;i < member.getMemberGames().size();i++){
                        if (num.equals(member.getMemberGames().get(i).getGame_name())) {
                            memberGameId = member.getMemberGames().get(i).getMember_game_id()+"";
                        }
                    }
                    tv_play_game.setText(num);
                }
            }
            if (requestCode == 2) {
                String t1;
                Calendar calendar;
                String picker_right = data.getStringExtra("picker_right");
                if (!"明天".equals(num)) {
                    t1 = sdfDD.format(new Date());
                    if ("".equals(picker_right)) {
                        calendar = Calendar.getInstance();
                        calendar.setTime(new Date());
                        calendar.add(Calendar.HOUR_OF_DAY, +1);
                        t1 = t1+sdfHH.format(calendar.getTime());
                    }else {
                        t1 = t1+picker_right;
                    }
                }else {
                    calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.DAY_OF_MONTH, +1);
                    t1 = sdfDD.format(calendar.getTime());
                    if ("".equals(picker_right)) {
                        t1 = t1+"12:00";
                    }else {
                        t1 = t1+picker_right;
                    }
                }
                playStartTime = t1;
                tv_play_date.setText(t1);
            }
            if (requestCode == 3) {
                if ("".equals(num)) {
                    hoursNum = "1";
                    tv_play_date_num.setText("1小时");
                }else {
                    hoursNum = num.substring(0,1);
                    tv_play_date_num.setText(num);
                }
            }
            if (requestCode == 4) {
                if ("".equals(num)) {
                    merchantId = member.getMerchants().get(0).getMerchantId()+"";
                    tv_play_address.setText(member.getMerchants().get(0).getMerchantName());
                }else {
                    for (int i = 0;i < member.getMerchants().size();i++){
                        if (num.equals(member.getMerchants().get(i).getMerchantName())) {
                            merchantId = member.getMerchants().get(i).getMerchantId()+"";
                        }
                    }
                    tv_play_address.setText(num);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initDate() {
        imageLoader.displayImage(ApiInterface.IMAGES + member.getMember_img(), iv_play_user_img, App.options);
        tv_play_user_name.setText(member.getMember_name());
        ll_play_user.removeAllViews();
        ImageView iv_play_user_game;TextView tv_play_user_game;
        for (int i = 0; i < member.getMemberGames().size(); i++) {
            LinearLayout linearLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.item_play_member_game,null);
            iv_play_user_game = (ImageView) linearLayout.findViewById(R.id.iv_play_user_game);
            tv_play_user_game = (TextView) linearLayout.findViewById(R.id.tv_play_user_game);
            imageLoader.displayImage(ApiInterface.IMAGES + member.getMemberGames().get(i).getGame_logo(), iv_play_user_game, App.options);
            tv_play_user_game.setText(member.getMemberGames().get(i).getDan());
            //添加点到view上
            ll_play_user.addView(linearLayout);
        }

        tv_play_game.setText(member.getMemberGames().get(0).getGame_name());
        memberGameId = member.getMemberGames().get(0).getMember_game_id()+"";

        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR_OF_DAY,+1);
        String t1 = sdf.format(calendar.getTime());
        playStartTime = t1+":00";
        tv_play_date.setText(playStartTime);
        hoursNum = "1";
        tv_play_date_num.setText(hoursNum+"小时");
        merchantId = member.getMerchants().get(0).getMerchantId()+"";
        tv_play_address.setText(member.getMerchants().get(0).getMerchantName());
        tv_play_phone.setText(userPhone);
    }

    private MyHttpClientRespenseHandler orderHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                try {
                    JSONObject jsonObject = json.optJSONObject("data").getJSONObject("order");
                    orderNo = jsonObject.getString("order_no");
                    subject = "";
                    price = jsonObject.getString("order_all_price");
                    toPlayActivity();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler indexHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            JSONArray itemArray;
            List<MemberGame> memberGames = null;
            if (succeed == 1) {
                merchants.clear();
                try {

                    itemArray = json.getJSONObject("data").getJSONArray("merchants");
                    if (itemArray != null){
                        for(int i = 0;i < itemArray.length();i++) {
                            JSONObject jsonObject = itemArray.getJSONObject(i);
                            Merchant merchant = new Merchant();
                            merchant.setMerchantId(jsonObject.getInt("merchantId"));
                            merchant.setMerchantName(jsonObject.getString("merchantName"));
                            merchant.setAddressDetail(jsonObject.getString("addressDetail"));
                            merchant.setAddressIntro(jsonObject.getString("addressIntro"));
                            merchant.setStartTime(jsonObject.getString("startTime"));
                            merchant.setEndTime(jsonObject.getString("endTime"));
                            merchants.add(merchant);
                        }
                    }
                    member.setMerchants(merchants);
                    JSONObject subItemObject = json.getJSONObject("data").getJSONObject("member");
                    member.setMember_id(subItemObject.optInt("member_id", 0));
                    member.setMember_img(subItemObject.optString("member_img"));
                    member.setMember_name(subItemObject.optString("member_name"));
                    itemArray = subItemObject.getJSONArray("memberGames");
                    if (itemArray != null){
                        memberGames = new ArrayList<>();
                        for(int i = 0;i < itemArray.length();i++) {
                            JSONObject jsonObject = itemArray.getJSONObject(i);
                            MemberGame memberGame = new MemberGame();
                            memberGame.setDan(jsonObject.getString("dan"));
                            memberGame.setGame_logo(jsonObject.optString("game_logo"));
                            memberGame.setGame_id(jsonObject.getInt("game_id"));
                            memberGame.setMember_game_id(jsonObject.getInt("member_game_id"));
                            memberGame.setGame_name(jsonObject.getString("game_name"));
                            memberGames.add(memberGame);
                        }
                    }
                    member.setMemberGames(memberGames);
                    initDate();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };
}
